function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
  this.next = null;
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function (root) {
  // 层次遍历
  function levelTraversal(root) {
    let queue = [{
        node: root,
        level: 0
      }],
      stack = [],
      arr = [];
    while (queue.length > 0 || stack.length) {
      let obj;
      if (queue.length) {
        obj = queue[0]
      } else {
        queue = stack.reverse();
        continue;
      }
      queue.splice(0, 1);
      if (obj.node == null)
        continue;
      if (arr[obj.level]) {
        arr[obj.level].push(obj.node);
      } else {
        arr[obj.level] = [obj.node];
      }
      queue.push({
        node: obj.node.left,
        level: obj.level + 1
      });
      queue.push({
        node: obj.node.right,
        level: obj.level + 1
      });

    }
    for(let i = 0; i < arr.length; i++) {
      for(let j = 0; j < arr[i].length - 1; j++) {
        arr[i][j].next = arr[i][j + 1];
      }
    }
    return arr;
  }
  // root = createTree(root);
  if(root == null)
    return root;
  let result = levelTraversal(root);
  return result[0][0];
};
let root = [1, 2, 3, 4, 5, 6, 7];
console.log(connect(root));
root = [];
console.log(connect(root));
